import {
  SHOW_ATTENDING, SHOW_ALL, SHOW_WITH_GUESTS, ADD_GUEST, REMOVE_GUEST, TOGGLE_ATTENDING,
  ADD_PERSON, REMOVE_PERSON
} from "./actions";

const details = (/* person */state, action) => {
  switch (action.type) {
    case ADD_GUEST: {
      if (state.id === action.payload) {
        return Object.assign({}, state, {guests: state.guests + 1})
      }
      return state
    }
    case REMOVE_GUEST: {
      if (state.id === action.payload) {
        return Object.assign({}, state, {guests: state.guests - 1})
      }
      return state
    }
    case TOGGLE_ATTENDING: {
      if (state.id === action.payload) {
        return Object.assign({}, state, {attending: !state.attending})
      }
      return state
    }
    default: {
      return state
    }
  }
}

export const people = (state = [], action) => {
  switch (action.type) {
    case ADD_PERSON:
      return [
        ...state,
        Object.assign({}, {id: action.payload.id, name: action.payload.name, guests: 0, attending: false})
      ]
    case REMOVE_PERSON: {
      if (action.payload !== undefined) {
        return state.filter(person => person.id !== action.payload)
      } else {
        return state
      }
    }
    case ADD_GUEST:
    case REMOVE_GUEST:
    case TOGGLE_ATTENDING:
      return state.map(person => details(person, action))
    default:
      return state
  }
}

export const partyFilter = (state = person => person, action) => {
  switch (action.type) {
    case SHOW_ATTENDING:
      return person => person.attending
    case SHOW_ALL:
      return person => person
    case SHOW_WITH_GUESTS:
      return person => person.guests
    default:
      return state
  }
}
